import AreaSelect from '@/components/AreaSelect';
import TopBread from '@/layouts/TopBread';
import { addBusiness, uploadImage } from '@/services/business';
import { registerUer, updBuy, updShop, uploadImageUser } from '@/services/user';
import { getQueryParams, selectOne } from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import { Anchor, Button, Form, Input, message, Modal, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import type { RcFile, UploadFile } from 'antd/es/upload/interface';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useLocation } from 'react-router';
import { history } from 'umi';
import ChangePassword from './components/ChangePassword';
import styles from './index.less';
import SeeModal from './SeeModal';

type AddressInfoType = {
  provinceName: string; // 省
  cityName: string; // 市
  countyName: string; // 区
};

const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const MerchantRegistered: React.FC = () => {
  const [form] = Form.useForm();
  const { userRole, lastRoute }: any = history?.location?.query;
  const location = useLocation();
  const qs = getQueryParams();
  const ifChange =
    location.pathname.includes('changeInformation') || location.pathname.includes('shopChange');
  const formRef = useRef<any | undefined>();
  const [current, setCurrent] = useState<string>('#0');
  const [isSee, setIsSee] = useState<boolean>(false);
  const [passwordModal, setPasswordModal] = useState<boolean>(false);
  const [previewOpen, setPreviewOpen] = useState<boolean>(false);
  const [previewImage, setPreviewImage] = useState<string>('');
  const [clickUpload, setClickUpload] = useState<string>('');
  const [fileListInto, setFileListInto] = useState<any[]>([]);
  const [avatarImg, setAvatarImg] = useState<string>(qs.avatar ? qs.avatar : '');
  const [isUploading, setIsUploading] = useState<boolean>(true);

  // 需要的一些地址信息（其中包括省、市、区、街道、地区码等）
  const [addressInfo, setAddressInfo] = useState<AddressInfoType>({
    // ... 一些别的信息
    provinceName: '',
    cityName: '',
    countyName: '',
  });

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };

  const NAVIGATION = [
    {
      name: '经营信息',
    },
    {
      name: '店铺信息',
    },
    {
      name: userRole === 'shop' || userRole === 'return' ? '联系人信息' : '个人信息',
    },
    {
      name: '服务协议',
    },
  ];

  const { provinceName, cityName, countyName } = addressInfo;
  // 选中的值  使用的时候用 useMemo 记录一下
  const areaValue = useMemo(
    () => [provinceName, cityName, countyName],
    [provinceName, cityName, countyName],
  );

  // areaChange 的回调方法
  const areaChange = (e?: string[]) => {
    // e2?: areaItemType[]   ↑
    setAddressInfo((v) => ({
      ...v,
      provinceName: e?.[0] ?? '',
      cityName: e?.[1] ?? '',
      countyName: e?.[2] ?? '',
    }));
  };

  useEffect(() => {
    if (userRole === 'shopChange') {
      setAddressInfo((v) => ({
        ...v,
        provinceName: qs.province,
        cityName: qs.city,
        countyName: qs.area,
      }));
    }
  }, [qs.area, qs.city, qs.province, userRole]);

  const beforeUpload = async (file: RcFile) => {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('请选择小于1M的图片上传！');
      return Upload.LIST_IGNORE;
    }
    await uploadImage({
      file,
    }).then((res) => {
      if (clickUpload !== 'intoPicture') {
        form.setFieldValue(clickUpload, res);
        if (clickUpload === 'saleLogo') {
          setAvatarImg(res);
          form.setFieldValue(clickUpload, res);
        }
      } else {
        let arr = fileListInto;
        arr.push({ id: res, fileName: file.name });
        setFileListInto(arr);
        if (arr.length >= 3) {
          setIsUploading(false);
        }
      }
    });
    return false;
  };

  const beforeUploadUser = async (file: RcFile) => {
    const isLt1M = file.size / 1024 / 1024 < 2;
    if (!isLt1M) {
      message.error('请选择小于1M的图片上传！');
      return Upload.LIST_IGNORE;
    }
    await uploadImageUser({
      file,
    }).then((res) => {
      form.setFieldValue('avatar', res);
      setAvatarImg(res);
    });
    return false;
  };

  const uploadButtonUpload = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传照片</div>
    </div>
  );

  const uploadButtonUploadUser = (
    <div className={styles.uploadButtonUploadUser}>
      <PlusOutlined />
      <div style={{ marginTop: 8, width: 100 }}>上传照片</div>
    </div>
  );

  const handlePreview = async (file: UploadFile) => {
    if (clickUpload !== 'avatar') {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj as RcFile);
      }
      setPreviewImage(file.url || (file.preview as string));
    }
    setPreviewOpen(true);
  };

  /**
   * 商家注册
   * @param values
   */
  const confirmSubmitBusiness = async (values: any) => {
    try {
      await addBusiness(values).then(() => {
        history.push({
          pathname: '/login&register',
        });
        message.success('申请成功，等待管理员审批！');
        localStorage.removeItem('qs');
      });
    } catch (error) {
      console.log(error);
    }
  };

  /**
   * 买家注册
   * @param values
   */
  const confirmSubmit = async (values: any) => {
    try {
      await registerUer(values).then(() => {
        history.push({
          pathname: '/login&register',
        });
        message.success('注册成功！');
      });
    } catch (error) {
      console.log(error);
    }
  };

  /**
   * 买家修改信息
   * @param values
   */
  const updBuySubmit = async (values: any) => {
    try {
      await updBuy({ ...values, isMoney: '0' }).then(() => {
        history.push({
          pathname: '/',
        });
        message.success('修改成功！');
        selectOne('1');
      });
    } catch (error) {
      console.log(error);
    }
  };

  /**
   * 商家修改信息
   * @param values
   */
  const updShopSubmit = async (values: any) => {
    try {
      await updShop(values).then(() => {
        history.push({
          pathname: '/back',
        });
        message.success('修改成功！');
        selectOne('2');
      });
    } catch (error) {
      console.log(error);
    }
  };

  const getIntoArr = () => {
    let arr: any[] = [];
    fileListInto.map((item) => {
      arr.push(item.id);
    });
    return arr;
  };

  const onFinishBusiness = async (values: any) => {
    await form.validateFields();
    values.province = addressInfo.provinceName;
    values.city = addressInfo.cityName;
    values.area = addressInfo.countyName;
    values.intoPicture = JSON.stringify(getIntoArr());
    if (userRole === 'return') {
      values.userId = qs.id;
    } else {
      values.userId = '6';
    }

    confirmSubmitBusiness(values);
  };

  const onFinish = async (values: any) => {
    await form.validateFields();
    values.role = '1';
    if (userRole === 'changeUser') {
      values.id = qs.id;
    } else if (userRole === 'shopChange') {
      values.province = addressInfo.provinceName;
      values.city = addressInfo.cityName;
      values.area = addressInfo.countyName;
      values.id = qs.id;
      values.role = '2';
    }
    // if (
    //   form.getFieldValue('nickname') === qs.nickname &&
    //   form.getFieldValue('tel') === qs.tel &&
    //   form.getFieldValue('mail') === qs.mail &&
    //   avatarImg === qs.avatar
    // ) {
    //   message.error('暂无可提交的修改内容');
    // } else {
    switch (userRole) {
      case 'changeUser':
        updBuySubmit(values);
        break;
      case 'buy':
        confirmSubmit(values);
        break;
      case 'shopChange':
        updShopSubmit(values);
        break;
      default:
        break;
    }
    // }
  };
  const onChange = (link: any) => {
    if (link === '#0' || !link) {
      setCurrent('#0');
    } else {
      setCurrent(link);
    }
  };
  const handleCancel = () => {
    setIsSee(false);
    isSee &&
      form.setFields([
        {
          name: 'protocol',
          value: 1,
        },
      ]);
  };

  const handleSee = () => {
    setIsSee(true);
    isSee &&
      form.setFields([
        {
          name: 'protocol',
          value: 1,
        },
      ]);
  };

  return (
    <div className={styles.allContent}>
      <TopBread
        lastRoute={lastRoute}
        now={!ifChange ? '注册' : userRole === 'shopChange' ? '修改注册信息' : '修改个人信息'}
        setColorParent={''}
      />
      <div className={styles.container}>
        <Form
          form={form}
          onFinish={userRole === 'shop' || userRole === 'return' ? onFinishBusiness : onFinish}
          ref={formRef}
          initialValues={{
            nickname: qs.nickname,
            tel: qs.tel,
            mail: qs.mail,
            pwd: qs.pwd,
            avatar: qs.avatar,
            addressDetail: qs.addressDetail,
            saleLogo: qs.avatar,
          }}
        >
          {(userRole === 'shop' || userRole === 'return') && (
            <div className={styles.formStyles} id="0">
              <h3>经营信息</h3>
              <Form.Item
                label="店铺名称"
                name="saleName"
                {...formItemLayout}
                rules={[
                  { required: true, message: '请输入店铺名称' },
                  { max: 15, message: '最多可输入15个字符' },
                  { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '限输入汉字、数字、字母' },
                ]}
              >
                <Input placeholder="请输入店铺/经营品牌名称" />
              </Form.Item>
              <Form.Item
                label="营业执照"
                name="certificate"
                {...formItemLayout}
                rules={[{ required: true, message: '请上传营业执照' }]}
                extra="仅支持jpg.png格式，图片需清晰完整，大小在1M以内"
              >
                <div
                  onClick={() => {
                    setClickUpload('certificate');
                  }}
                >
                  <Upload
                    maxCount={1}
                    onPreview={handlePreview}
                    accept=".jpg, .png"
                    action="'@/assets/upload'"
                    listType="picture-card"
                    beforeUpload={beforeUpload}
                    onRemove={() => {
                      form.setFieldValue(clickUpload, '');
                    }}
                  >
                    {uploadButtonUpload}
                  </Upload>
                </div>
              </Form.Item>
              <Form.Item
                label="店铺内景照片"
                name="intoPicture"
                {...formItemLayout}
                extra="仅支持jpg.png格式，图片需清晰完整，大小在1M以内，最多上传三张"
                rules={[{ required: true, message: '请上传店铺内景照片' }]}
                className={styles.shopPhoto}
              >
                <div
                  style={{ display: 'flex' }}
                  onClick={() => {
                    setClickUpload('intoPicture');
                  }}
                >
                  <Upload
                    action="'@/assets/upload'"
                    accept=".jpg, .png"
                    listType="picture-card"
                    onPreview={handlePreview}
                    maxCount={3}
                    beforeUpload={beforeUpload}
                    onRemove={(file) => {
                      let arr: any = [];
                      let index = 0;
                      fileListInto.map((item) => {
                        if (item.fileName !== file.name || index !== 0) {
                          arr.push(item);
                        } else {
                          index++;
                        }
                      });
                      if (arr.length < 3) {
                        setIsUploading(true);
                      }
                      setFileListInto(arr);
                    }}
                  >
                    {!isUploading ? '' : uploadButtonUpload}
                  </Upload>
                </div>
              </Form.Item>
            </div>
          )}
          {(userRole === 'shop' || userRole === 'return' || userRole === 'shopChange') && (
            <div className={styles.formStyles} id="1">
              <h3>店铺信息</h3>
              <Form.Item
                label="上传店铺logo"
                name="saleLogo"
                {...formItemLayout}
                extra="仅支持jpg.png格式，图片需清晰完整，大小在1M以内"
                rules={[{ required: true, message: '请上传店铺logo' }]}
              >
                <div
                  onClick={() => {
                    setClickUpload('saleLogo');
                  }}
                >
                  <ImgCrop>
                    <Upload
                      maxCount={1}
                      onPreview={handlePreview}
                      accept=".jpg, .png"
                      action="'@/assets/upload'"
                      beforeUpload={beforeUpload}
                      onRemove={() => {
                        form.setFieldValue(clickUpload, '');
                        setAvatarImg('');
                      }}
                    >
                      {avatarImg === '' ? (
                        uploadButtonUploadUser
                      ) : (
                        <img
                          alt=""
                          style={{ width: 102 }}
                          src={`http://localhost:8090/dyh/upload_images/business/${avatarImg}`}
                        />
                      )}
                    </Upload>
                  </ImgCrop>
                </div>
              </Form.Item>
              <Form.Item label="店铺地址" name="area" {...formItemLayout}>
                <div>
                  <AreaSelect type="area" value={areaValue} onChange={areaChange} />
                </div>
                <Form.Item
                  name="addressDetail"
                  rules={[{ required: true, message: '请输入店铺地址' }]}
                >
                  <Input placeholder="请输入详细地址" max={100} showCount />
                </Form.Item>
              </Form.Item>
            </div>
          )}
          <div className={styles.formStyles} id="2">
            <h3>{userRole === 'shop' || userRole === 'return' ? '联系人信息' : '个人信息'}</h3>
            <Form.Item
              label="姓名"
              name="nickname"
              {...formItemLayout}
              rules={[
                { required: true, message: '请输入联系人姓名' },
                { max: 20, message: '姓名的长度在2-20之间' },
                { min: 2, message: '姓名的长度在2-20之间' },
                { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '限输入汉字、数字、字母' },
              ]}
            >
              <Input placeholder="请输入联系人姓名" />
            </Form.Item>
            {userRole !== 'shop' && userRole !== 'return' && userRole !== 'shopChange' && (
              <Form.Item
                label={'头像'}
                name="avatar"
                {...formItemLayout}
                extra="仅支持jpg.png格式，图片需清晰完整，大小在1M以内"
                rules={[{ required: true, message: '请上传您的头像' }]}
                className={styles.shopPhoto}
              >
                <div
                  onClick={() => {
                    setClickUpload('avatar');
                  }}
                >
                  <ImgCrop>
                    <Upload
                      action="'@/assets/upload'"
                      accept=".jpg, .png"
                      onPreview={handlePreview}
                      maxCount={1}
                      beforeUpload={beforeUploadUser}
                      onRemove={() => {
                        form.setFieldValue(clickUpload, '');
                        setAvatarImg('');
                      }}
                    >
                      {avatarImg === '' ? (
                        uploadButtonUploadUser
                      ) : (
                        <img
                          alt=""
                          style={{ width: 102 }}
                          src={`http://localhost:8090/dyh/upload_images/user/${avatarImg}`}
                        />
                      )}
                    </Upload>
                  </ImgCrop>
                </div>
              </Form.Item>
            )}
            <Form.Item
              label="手机号码"
              name="tel"
              {...formItemLayout}
              rules={[
                { required: true, message: '请输入联系人手机号码' },
                { pattern: /^1[0-9]{10}$/, message: '请输入正确的手机号' },
              ]}
            >
              <Input placeholder="请输入联系人手机号码" disabled={userRole === 'return'} />
            </Form.Item>
            <Form.Item
              label="电子邮箱"
              name="mail"
              {...formItemLayout}
              rules={[
                { required: true, message: '请输入联系人电子邮箱' },
                {
                  pattern:
                    /^[A-Za-z\d]{1,20}([-_.][A-Za-z\d]{1,20})*@(([A-Za-z\d]{1,11})[-.])+[A-Za-z\d]{2,4}$/,
                  message: '请输入正确的邮箱,邮箱前缀最多输入20个字符，后缀最多输入15个字符',
                },
              ]}
            >
              <Input placeholder="请输入联系人电子邮箱" disabled={userRole === 'return'} />
            </Form.Item>
            {!(userRole === 'changeUser' || userRole === 'changeBuy') && (
              <Form.Item
                label="密码"
                name="pwd"
                {...formItemLayout}
                rules={[
                  { required: true, message: '请设置您的密码' },
                  {
                    pattern:
                      /^S*(?=\S{9,})(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/,
                    message: (
                      <div>
                        <div>长度为9~16个字符</div>
                        <div>必须包含大小写字母，数字或特殊符号任意3项!</div>
                      </div>
                    ),
                  },
                ]}
              >
                <Input placeholder="请设置您的密码" />
              </Form.Item>
            )}
            {(userRole === 'changeUser' || userRole === 'changeBuy') && (
              <Form.Item label="是否修改密码" name="newPassword" {...formItemLayout}>
                <Button
                  onClick={() => {
                    setPasswordModal(true);
                  }}
                >
                  点击修改
                </Button>
              </Form.Item>
            )}
          </div>
          {ifChange ? (
            ''
          ) : (
            <div className={styles.formStyles} id="3">
              <h3>服务协议</h3>
              <Form.Item
                label="服务协议"
                name="protocol"
                {...formItemLayout}
                className={form.getFieldValue('protocol') === 1 && styles.protocol}
                rules={[{ required: true, message: '请查看服务协议' }]}
              >
                <a className={styles.agreement} onClick={handleSee}>
                  {userRole === 'shop' || userRole === 'return'
                    ? '《四季养生卖家服务协议》'
                    : '《四季养生平台服务协议》'}
                </a>
              </Form.Item>
            </div>
          )}
          <Button
            type="primary"
            className={styles.button}
            htmlType="submit"
            onClick={userRole === 'shop' || userRole === 'return' ? onFinishBusiness : onFinish}
          >
            {ifChange ? '修改' : '提交'}
          </Button>
        </Form>
        {(userRole === 'shop' || userRole === 'return') && (
          <div className={styles.targetMenu}>
            <Anchor onChange={onChange} showInkInFixed={false} affix={false}>
              {NAVIGATION.map((item: any, index: number) => (
                <Anchor.Link
                  key={item.name}
                  href={`#${index}`}
                  title={item.name}
                  className={current === `#${index}` ? styles.current : ''}
                />
              ))}
            </Anchor>
          </div>
        )}
        {isSee && <SeeModal handleCancel={handleCancel} userRole={userRole} />}
        {passwordModal && (
          <ChangePassword
            handleCancel={() => {
              setPasswordModal(false);
            }}
            visible={passwordModal}
            password={qs.pwd}
          />
        )}
        <Modal
          open={previewOpen}
          title={
            clickUpload === 'certificate'
              ? '营业执照'
              : clickUpload === 'intoPicture'
              ? '店铺内景照片'
              : clickUpload === 'saleLogo'
              ? '店铺logo'
              : '头像预览'
          }
          footer={null}
          onCancel={() => {
            setPreviewOpen(false);
          }}
        >
          {clickUpload !== 'avatar' ? (
            <img alt="example" style={{ width: '100%' }} src={previewImage} />
          ) : (
            <img
              alt=""
              style={{ width: '100%' }}
              src={`http://localhost:8090/dyh/upload_images/user/${form.getFieldValue('avatar')}`}
            />
          )}
        </Modal>
      </div>
    </div>
  );
};

export default MerchantRegistered;
